package com.listener;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamUtils;
import com.github.sarxos.webcam.util.ImageUtils;
import com.thread.RunVideoThread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Author：hanll
 * ClassName：VCListener
 * Date：2022/11/1 11:01
 * Version：1.0
 * Description：
 */
public class VCListener implements ActionListener {

    private Graphics graphics = null;

    public void setVCListener(Graphics graphics) {
        this.graphics = graphics;
    }

    private Webcam webcam = null;

    private RunVideoThread runVideoThread;

    @Override
    public void actionPerformed(ActionEvent e) {
        String str = e.getActionCommand();
        if (str.equals("启动")) {
            webcam = Webcam.getDefault();
            webcam.open();
            runVideoThread = new RunVideoThread(webcam, graphics);
            runVideoThread.open();
            Thread thread = new Thread(runVideoThread);
            thread.start();
        } else if (str.equals("关闭")) {
            webcam.close();
            runVideoThread.close();
        } else if (str.equals("拍照")) {
            String fileName = "D:\\" + System.currentTimeMillis();
            WebcamUtils.capture(webcam, fileName, ImageUtils.FORMAT_JPG);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JOptionPane.showConfirmDialog(null, "拍照成功");
                }
            });
        }
    }
}
